package com.xu.a2019;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author by yaodao,
 * @date on 2018/10/10.
 * PS: Not easy to write code, please indicate.
 */
public abstract class BaseListViewAdapter<T> extends BaseAdapter {
    protected Context mContext;

    public List<T> getData() {
        return mList;
    }

    protected List<T> mList;

    public BaseListViewAdapter(Context context, List<T> list) {
        this.mContext = context;
        this.mList =list;
    }

    public void addData(List<T> list) {
        if (mList == null) {
            mList = new ArrayList<>();
        }
        mList.addAll(list);
    }

    public void initData(List<T> list) {
        if (mList == null) {
            mList = new ArrayList<>();
        } else {
            mList.clear();
        }
        mList.addAll(list);
    }


    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList == null ? null : mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseViewHolder holder = BaseViewHolder.getInstance(mContext, convertView, setContentView(position));
        // 子类重写的方法，完成holder中view的初始化
        convert(holder, mList.get(position));
        return holder.getConvertView();
    }

    /**
     * 绘制界面
     *
     * @param position 当前位置
     * @return xml布局
     */
    protected abstract int setContentView(int position);


    /**
     * 子类必须重写的方法，通过这个方法初始化holder中的View即可
     *
     * @param holder 返回的holder
     * @param t      第i个数据
     */
    public abstract void convert(BaseViewHolder holder, T t);


}
